package com.zsck.zsgy.util;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.blankj.utilcode.util.LogUtils;
import com.zsck.zsgy.R;
import com.zsck.zsgy.ui.guide.bean.CurrentOrLastCityBean;

import java.util.List;
import java.util.Locale;

import static com.zsck.zsgy.util.APPBineseExtKt.sendLiveEventData;
import static com.zsck.zsgy.util.LiveTagKt.LOCATION;
import static com.zsck.zsgy.util.LiveTagKt.LOCATIONINFO;

/**
 * 创建者     Bowllboy
 * 创建时间   2020/5/11 16:47
 * 描述	      地理位置信息
 */
public class LocationUtils {

    private volatile static LocationUtils uniqueInstance;
    private LocationManager locationManager;
    private Location location;
    private Context mContext;
//    public static final int CITY_CODE = 100;

    private LocationUtils(Context context) {
        mContext = context;
        initLocation();
    }

    //采用Double CheckLock(DCL)实现单例
    public static LocationUtils getInstance(Context context) {
        if (uniqueInstance == null) {
            synchronized (LocationUtils.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new LocationUtils(context);
                }
            }
        }
        return uniqueInstance;
    }

    private void initLocation() {
        //1.获取位置管理器
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        //2.获取位置提供器，GPS或是NetWork
        List<String> providers = locationManager.getProviders(true);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String localProvider = locationManager.getBestProvider(criteria, true);
        // 需要检查权限,否则编译报错,。
        if (Build.VERSION.SDK_INT >= 23 &&
                ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        for (String provider : providers) {
            //3.获取上次的位置，一般第一次运行，此值为null
            Location l = locationManager.getLastKnownLocation(provider);
            if (provider != null && localProvider == null) {
                localProvider = provider;
            }
            if (l == null) {
                continue;
            }
            if (location == null || l.getAccuracy() < location.getAccuracy()) {
                // Found best last known location: %s", l);
                location = l;
            }
        }
        if (location != null) {
            setLocation(location);
        }
        if(localProvider == null){
            return;
        }
        // 监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
        locationManager.requestLocationUpdates(localProvider, 60, 1000, locationListener);
    }

    private void setLocation(Location location) {
        this.location = location;
        String address = "纬度：" + location.getLatitude() + "经度：" + location.getLongitude();
//        Log.d( TAG, address );
    }

    /**
     * 获取地址
     */
    public String getUserAddress(double latitude, double longtitude){
        LatLng latLng= new LatLng(latitude,longtitude);
        final String[] address = new String[1];
        GeoCoder geoCoder = GeoCoder.newInstance();
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latLng).pageNum(0).pageSize(10));
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                LogUtils.e("reverseGeoCodeResult:"+reverseGeoCodeResult.toString());
                if (reverseGeoCodeResult == null
                        || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    // 没有检测到结果
                    return;
                }
                LogUtils.e(""+reverseGeoCodeResult.getAddress()+"");
                ReverseGeoCodeResult.AddressComponent addressDetail = reverseGeoCodeResult.getAddressDetail();
                LogUtils.e("city"+addressDetail.city+"street"+addressDetail.street+"direction"+addressDetail.direction);

                address[0] = reverseGeoCodeResult.getAddress();
            }
        });
        return address[0];
    }
    // 获取地址信息

    public void getAddress() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
                CurrentOrLastCityBean bean = new CurrentOrLastCityBean();
                String city = mContext.getString(R.string.city_sz);
                if (location == null) {
                    sendLiveEventData(new LiveDataEvent(LOCATION,city));
                    return;
                }
                try {
                    List<Address> addresses = geocoder.getFromLocation(location.getLatitude(),
                            location.getLongitude(), 1);
                    if (addresses.size() > 0) {
                        Address address = addresses.get(0);
                        String cityInfo ="";
                        if(!TextUtils.isEmpty(address.getSubAdminArea())&&address.getSubAdminArea().endsWith("市")){
                            cityInfo = address.getSubAdminArea();
                        }else{
                            cityInfo = address.getLocality();
                        }
                        if(cityInfo.endsWith("市")){
                            cityInfo = cityInfo.substring(0, cityInfo.length() - 1);
                        }

                        sendLiveEventData(new LiveDataEvent(LOCATIONINFO,cityInfo));
                    } else {
                        sendLiveEventData(new LiveDataEvent(LOCATION,city));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                bean.setCity(city);
                bean.setLatitude(location.getLatitude());
                bean.setLongitude(location.getLongitude());
                LogUtils.e("位置信息： "+bean.toString());
                PrefserHelper.saveCurrentCity(bean);
                sendLiveEventData(new LiveDataEvent(LOCATION,city));
            }
        }).start();

    }

    //获取经纬度
    public Location getLocation() {
        return location;
    }

    // 移除定位监听
    public void removeLocationUpdatesListener() {
        // 需要检查权限,否则编译不过
        if (Build.VERSION.SDK_INT >= 23 &&
                ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (locationManager != null) {
            uniqueInstance = null;
            locationManager.removeUpdates(locationListener);
        }
    }

    /**
     * LocationListern监听器
     * 参数：地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
     */

    LocationListener locationListener = new LocationListener() {

        /**
         * 当某个位置提供者的状态发生改变时
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {

        }

        /**
         * 某个设备打开时
         */
        @Override
        public void onProviderEnabled(String provider) {

        }

        /**
         * 某个设备关闭时
         */
        @Override
        public void onProviderDisabled(String provider) {

        }

        /**
         * 手机位置发生变动
         */
        @Override
        public void onLocationChanged(Location location) {
            location.getAccuracy();//精确度
            setLocation(location);
        }
    };

}
